//
//  SimpleSpinningCube.cpp
//  Nano
//
//  Created by Jeppe Nielsen on 8/22/13.
//  Copyright (c) 2013 Jeppe Nielsen. All rights reserved.
//

#include "Engine.hpp"
#include "GameState.hpp"
#include "GameWorld.hpp"
#include "RenderSystem.hpp"
#include "Touchable.hpp"
#include "Material.hpp"
#include "TextureComponent.hpp"
#include "FirstPersonMoverSystem.hpp"
#include "TouchSystem.hpp"
#include "Light.hpp"

using namespace Nano;

class SimpleSpinningCube : public GameState {
    void Initialized() {
        Input.TouchUp += event_handler(this, &SimpleSpinningCube::TouchUp);
        renderer = world.CreateSystem<RenderSystem>();
        world.CreateSystem<FirstPersonMoverSystem>()->Input = &Input;
        
        GameObject* camera = world.CreateObject();
        camera->AddComponent<Camera>()->Viewport = Viewport();
        camera->AddComponent<Transform>()->Position = Vector3(0,0,4);
        camera->AddComponent<FirstPersonMover>();
        
        ambientLight = world.CreateObject();
        ambientLight->AddComponent<Light>()->Type = LightType::Ambient;
        ambientLight->AddComponent<Colorable>()->Color = Colour(1.0f, 1.0f, 1.0f, 1.0f);
        
        light = world.CreateObject();
        light->AddComponent<Transform>()->Rotation = Quaternion(1, Vector3(1,1,1).Normalized());
        light->AddComponent<Light>();
        light->AddComponent<Mesh>()->AddCube(0, 1);
        light->GetComponent<Transform>()->Scale = Vector3(0.1f,0.1f,3.0f);
        light->AddComponent<Material>()->LightingEnabled = false;
        light->AddComponent<TextureComponent>()->Texture().LoadFromPng("grass.png");
        
        cube = world.CreateObject();
        cube->AddComponent<Transform>();
        cube->AddComponent<Mesh>()->AddGeoSphere(0, 1, 2);
        cube->AddComponent<Material>()->LightingEnabled = true;
        //cube->AddComponent<Colorable>()->Color = Colour::Blue();
        cube->AddComponent<TextureComponent>()->Texture().LoadFromPng("grass.png");
        
    }
    
    void Update(float dt) {
        static float rotation = 0;
        rotation+=dt;
        light->GetComponent<Transform>()->Rotation = Quaternion::Create(rotation, Vector3(1,1,0).Normalized());
        world.Update(dt);
    }
    
    void Render() {
        glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glEnable(GL_CULL_FACE);
        renderer->Render();
    }
    
    void TouchUp(TouchEvent e) {
        //Exit();
        
        float amount = (e.Position.x / ScreenSize().x);
        
        cout<<amount<<endl;
        
        //ambientLight->GetComponent<Colorable>()->Color = Colour(amount, 0, 0,1.0f);
        light->GetComponent<Light>()->Intensity = amount * 10;
        
    }
    
    GameWorld world;
    RenderSystem* renderer;
    GameObject* cube;
    GameObject* light;
    GameObject* ambientLight;
};

/*
int main() {
    Engine e;
    e.Start<SimpleSpinningCube>();
}
*/
